<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.saleId ? '编辑业务员' : '新增业务员' }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="userName" label="账号" v-if="dataForm.saleId">
              <el-input type="text" v-model="dataForm.userName" :disabled="true"></el-input>
            </el-form-item>
          <el-form-item prop="nickName" label="昵称" v-if="dataForm.saleId">
            <el-input v-model="dataForm.nickName"></el-input>
          </el-form-item>
          <el-form-item prop="fullName" label="姓名">
            <el-input v-model="dataForm.fullName"></el-input>
          </el-form-item>
          <el-form-item prop="sex" label="性别">
            <el-radio-group v-model="dataForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="phone" label="手机号">
            <el-input :read-only="$route.query.id" type="text" v-model="dataForm.phone"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="dataForm.email"></el-input>
          </el-form-item>
          <el-form-item prop="businessId" label="商户">
            <el-select placeholder="请选择商户" :disabled="dataForm.saleId?true:false" v-model="dataForm.businessId" clearable filterable
              @change="handleBusinessChange">
              <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name">

              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="remark" label="备注">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
          <el-form-item style="width:1000px" v-if="!dataForm.saleId">
            <span style="color: red;">说明：新增时，登录账号和昵称会自动生成，生成规则：登录账号=手机号，昵称=商户昵称+“-”+姓名</span>
          </el-form-item>

        </el-row>

        <div class="tit" v-show="dataForm.businessId">
          <h2>商户管理范围</h2>

        </div>
        <el-row v-show="dataForm.businessId">
          <el-table :data="businessVillages" style="width:fit-content">
            <el-table-column label="地区" prop="address" width="370" align="center">

            </el-table-column>
            <el-table-column label="小区" prop="villageName" align="center" width="300">

            </el-table-column>
          </el-table>
        </el-row>
        <div class="tit">
          <h2>管理范围</h2>
          <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtnRegion">
          </el-button>
        </div>
        <el-row>
          <el-table :data="dataForm.list" style="width:max-content;">
            <el-table-column label="操作" width="70" align="center">
              <template slot-scope="scope">
                <el-button icon="el-icon-minus" type="danger" plain size="medium" circle
                  @click="subBtnRegion(scope.$index)">
                </el-button>
              </template>
            </el-table-column>

            <el-table-column label="地区" width="320" align="center">
              <template slot-scope="scope">
                <Region style="width:300px" ref="region" :streetValues="scope.row.streetIds"
                  @regionChange="handleItemChange" :isChangeOnSelect="true" :index="scope.$index"></Region>
              </template>
            </el-table-column>
            <el-table-column label="小区" width="280" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.villageId" style="width: 240px;"
                  @focus="handleVillageFocus(scope.row.streetIds, scope.$index)"
                  @change="handleVillageChange(scope.row, scope.$index)" clearable>
                  <el-option v-for=" item  in  scope.row.villageList " :value="item.id" :label="item.name" :key="item.id">

                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>

    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import SalesmanApi from '@/api/business/salesman';
import BusinessApi from "@/api/business/business";
import { getStorage } from '@/utils/auth';
import { USER_INFO } from "@/constants/storeName";
import Region from "@/components/Region";
import VillageApi from "@/api/address/village";
import AdminVillageApi from "@/api/common/adminVillage"
import UploadImg from "@/components/UploadImg"
export default {
  data() {
    return {
      userInfo: "",
      list: [],
      dataForm: {
        saleId: "",
        saleType: 1,
        userName: "",
        // sysDepartId:"",
        fullName: "",
        sex: 1,
        businessId: "",
        nickName: "",
        phone: "",
        casUserId: "",
        email: "",
        userId: "",
        remark: "",
        list: [
          {
            provinceId: "",
            provinceName: "",
            cityId: "",
            cityName: "",
            areaId: "",
            areaName: "",
            streetId: '',
            streetName: "",
            villageId: "",
            villageName: "",
            levels: "",
            streetIds: [],//地区数组id,提交的时候要删掉
            villageList: [],//小区列表,提交的时候要删掉
          }
        ],

      },
      businessList: [],
      businessVillages: [],
      loadingIns: false,
      roleRules: {
        /*nickName: [
          { required: true, message: "请输人昵称", trigger: "blur" }
        ],*/
        fullName: [
          { required: true, message: "请输人真实姓名", trigger: "blur" }
        ],
        businessId: [
          { required: true, message: "请选择商户", trigger: "change" }
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: "手机号码格式错误", trigger: "blur" }
        ],
      },
      // sysDepartList:[],
    }
  },
  components: {
    Region, UploadImg
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 获取用户的信息
      this.userInfo = getStorage(USER_INFO)
      // 当是进来的是商户的时候因为不能选择商户这个字段，所以校验规则需要做改变去掉商户校验
      // if (this.userInfo.userRole == 3) {
      //   this.$delete(this.roleRulesAdd, "businessId")
      //   this.$delete(this.roleRulesEdit, "businessId")
      //   this.$nextTick(() => {
      //     // 调用nextTick生命周期函数避免
      //     this.$refs['dataForm'].resetFields();
      //   })
      // }

      this.getBusinessList()
      // this.getSysDepartList()
      if (this.$route.query.id) {
        this.dataForm.saleId = this.$route.query.id
        this.getData()
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    addBtnRegion() {
      this.dataForm.list.push({
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        areaName: "",
        streetId: '',
        streetName: "",
        villageId: "",
        villageName: "",
        levels: "",
        houseId: "",
        streetIds: [],
        villageList: [],
        houseList: [],
      })
    },
    subBtnRegion(index) {
      this.dataForm.list.splice(index, 1)
    },
    handleItemChange(val) {
      if (val.index === 0 || val.index) {
        // 当是列表里面的数据的时候，传了索引过去，所以接收索引
        let region = this.dataForm.list[val.index]
        region.villageList = [] //清空小区列表
        region.villageId = "" //清空对应的小区id
        region.villageName = ""//清空小区对应的名字
        region.houseId = "" //清空设备地址
        region.houseList = [] //清空设备地址列表
        region.levels = ""
        region.provinceId = val.provinceId;
        region.provinceName = val.provinceName;
        region.cityId = val.cityId;
        region.cityName = val.cityName;
        region.areaId = val.areaId;
        region.areaName = val.areaName;
        region.streetId = val.streetId
        region.streetName = val.streetName
        region.levels = val.levels

        if (val.provinceId) {
          region.streetIds = [
            val.provinceId,
            val.cityId,
            val.areaId,
            val.streetId,
          ];
        } else {
          region.streetIds = []
        }
      } else {
        // 没有传索引过去
        this.dataForm.provinceId = val.provinceId;
        this.dataForm.provinceName = val.provinceName;
        this.dataForm.cityId = val.cityId;
        this.dataForm.cityName = val.cityName;
        this.dataForm.areaId = val.areaId;
        this.dataForm.areaName = val.areaName;
        this.dataForm.streetId = val.streetId;
        this.dataForm.streetName = val.streetName;
        this.dataForm.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      }
    },
    handleVillageFocus(streetIds, index) {
      // 点击小区的时候调用接口
      // let levels = this.dataForm.list[index].levels
      // if (levels == 3 || levels == 4 || levels == 5) {
      streetIds = streetIds.filter(item => typeof item == "number") //有名字的话就要过滤掉
      let param = {
        provinceId: streetIds[0],
        cityId: streetIds[1],
        areaId: streetIds[2],
        streetId: streetIds[3],
        name: "",
      }
      VillageApi.villageList(param).then(res => {
        // this.$set(this.dataForm.businessVillages[index],"villageList",res.data)
        // this.dataForm.list[index].villageList = res.data
      })
      // }
    },
    handleVillageChange(row, index) {
      // 需要拿到小区的名字放在数组里一起传给后台
      let value = this.dataForm.list[index]
      value.houseId = ""
      value.houseList = []
      if (row.villageId) {
        let obj = value.villageList.find(item => item.id == row.villageId)
        value.villageName = obj.name
      } else {
        value.villageName = ""
      }
    },
    async handleBusinessChange() {
      const { dataForm: { businessId } } = this
      let res = []
      if (businessId) {
        res = await AdminVillageApi.listVillage({ businessId })
        res = res.data || []
        res.forEach(item => {
          item.address = (item.provinceName || "") + (item.cityName || "") + (item.areaName || "") + (item.streetName || "")
          // item.address
        })

      }
      this.businessVillages=res
    },
    getData() {
      SalesmanApi.getSalesmanInfo({
        id: this.dataForm.saleId
      }).then(res => {
        this.$Utils.bindingBean(this.dataForm, res.data)
        this.handleBusinessChange()
        this.dataForm.list = res.data.list.map(item => {
          let param = {
            provinceId: item.provinceId,
            provinceName: item.provinceName,
            cityId: item.cityId,
            cityName: item.cityName,
            areaId: item.areaId,
            areaName: item.areaName,
            streetId: item.streetId,
            streetName: item.streetName,
            villageId: item.villageId,
            villageName: item.villageName,
            levels: item.levels
          }
          if (item.villageId && item.villageName) {
            param.villageList = [{ id: item.villageId, name: item.villageName }]
          } else {
            param.villageList = []
          }
          return param
        })
        // 这里必须要使用nextTick函数否则Region组件不会渲染出来，且下面必须使用$set。
        this.$nextTick(() => {
          if (this.dataForm.list.length > 0) {
            this.dataForm.list.forEach((item, index) => {
              this.$set(item, "streetIds", [
                item.provinceId,
                item.provinceName,
                item.cityId,
                item.cityName,
                item.areaId,
                item.areaName,
                item.streetId,
                item.streetName
              ])
            })
          }
        })

      })
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo({ businessType: -9 }).then(res => {
        this.businessList = res.data
      })
    },
    // 判断地址是否相等
    judgeAddressEquip(obj1, obj2) {
      if (obj1.provinceId != obj2.provinceId && obj1.provinceId) return false
      if (obj1.cityId != obj2.cityId && obj1.cityId) return false
      if (obj1.areaId != obj2.areaId && obj1.areaId) return false
      if (obj1.streetId != obj2.streetId && obj1.streetId) return false
      if (obj1.villageId != obj2.villageId && obj1.villageId) return false
      return true
    },
    removeDup(salesmanVillageList) {
      const list = []
      salesmanVillageList.forEach(item => {
        if (!list.length || !list.some(item2 => this.judgeAddressEquip(item, item2))) {
          list.push(item)
        }
      })

      return list
    },
    sureClick() {



      this.$refs.dataForm.validate(valid => {
        if (valid) {
          // 对经营区域表进行处理，先去掉空的行，再判断是否至少加了一行数据(必须加)，最后过滤筛选出需要提交的数据
          //    if (this.dataForm.saleType == 2) {
          let salesmanVillageList = this.dataForm.list.filter(item => item.provinceId)
          if (salesmanVillageList.length == 0) {
            this.$message.error("请至少选择一个服务范围")
            return
          }
          // 地址去重
          this.dataForm.list = salesmanVillageList = this.removeDup(salesmanVillageList)
          // 这里必须要用一个新的数据接收,要过滤掉里面的数组
          this.salesmanVillageList = salesmanVillageList.map(item => {
            return {
              provinceId: item.provinceId,
              provinceName: item.provinceName,
              cityId: item.cityId,
              cityName: item.cityName,
              areaId: item.areaId,
              areaName: item.areaName,
              streetId: item.streetId,
              streetName: item.streetName,
              villageId: item.villageId,
              villageName: item.villageName,
              levels: item.villageId ? 5 : item.levels,  //需要在这里判断villageId如果存在levels就代表第五层小区
            }
          })
          this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
            .then(() => {
              if (this.dataForm.saleId) {
                this.editData();
              } else {
                this.addData();
              }
            });
        }
      })
    },
    addData() {
      let param = {
        userName: this.dataForm.userName,
        userId: this.dataForm.userId,
        cashUserId: this.dataForm.cashUserId,
        saleType: this.dataForm.saleType,
        fullName: this.dataForm.fullName,
        nickName: this.dataForm.nickName,
        sex: this.dataForm.sex,
        businessId: this.dataForm.businessId,
        phone: this.dataForm.phone,
        remark: this.dataForm.remark,
        saleType: this.dataForm.saleType,
        email: this.dataForm.email,
        list: this.salesmanVillageList
      };
      SalesmanApi.addSalesman(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData() {
      let param = {
        saleId: this.dataForm.saleId,
        userName: this.dataForm.userName,
        userId: this.dataForm.userId,
        casUserId: this.dataForm.casUserId,
        saleType: this.dataForm.saleType,
        fullName: this.dataForm.fullName,
        nickName: this.dataForm.nickName,
        sex: this.dataForm.sex,
        // userCode: this.dataForm.userCode,
        businessId: this.dataForm.businessId,
        email: this.dataForm.email,
        phone: this.dataForm.phone,
        remark: this.dataForm.remark,
        list: this.salesmanVillageList
      };
      SalesmanApi.editSalesman(param)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.back();
    }
  },

}
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
